#ifndef _MY_DATA_
#define _MY_DATA_
#include"util.hpp"
#include <unordered_map>
#include <sstream>

namespace cloud{

	class DataManager {
	private:
		std::string _backup_file;//备份信息的持久化存储文件
		std::unordered_map<std::string, std::string> _table;
		
	public:
		DataManager(const std::string& backup_file) :_backup_file(backup_file){
			InitLoad();
		}
		bool Storage() {
			//1.获取所有的备份信息
			auto it = _table.begin();
			std::stringstream ss ;
			for (; it != _table.end(); it++) {
				//2.将所有信息进行指定持久化格式的组织
				ss << it->first << " " << it->second << "\n";
			}
			
			//3.持久化存储
			FileUtil fu(_backup_file);
			fu.SetContent(ss.str());
			return true;
		}

		int Spilt(const std::string& str, const std::string& seq, std::vector<std::string>* arry) {
			int count = 0;
			size_t pos = 0, idx = 0;
			while (1) {
				pos = str.find(seq, idx);
				if (pos == std::string::npos) {
					break;
				}
				if (pos == idx) {
					idx = pos + seq.size();
					continue;
				}
				std::string tmp = str.substr(idx, pos - idx);
				arry->push_back(tmp);
				count++;
				idx = pos + seq.size();
			}
			if (idx < str.size()) {
				arry->push_back(str.substr(idx));
				count++;
			}
			return count;
		}
		bool InitLoad() {
			//1.从文件读取数据
			FileUtil fu(_backup_file);
			std::string body;
			fu.GetContent(&body);
			//2.进行数据解析，存入表
			std::vector<std::string>arry;
			Spilt("body", "\n", &arry);
			for (auto& a : arry) {
				// b.txt b.txt-34665-65266
				std::vector<std::string> tmp;
				Spilt(a, " ", &tmp);
				if (tmp.size() != 2) {
					continue;
					}
				_table[tmp[0]] = tmp[1];//存入
			}

			return true;
		}
		bool Insert(const std::string& key, const std::string& val) {
			_table[key] = val;
			Storage();
			return true;
		}
		bool Updata(const std::string& key, const std::string& val) {
			_table[key] = val;
			Storage();
			return true;
		}
		bool GetOneByKey(const std::string key, std::string* val) {
			auto it = _table.find(key);
			if (it == _table.end()) {
				return false;
			}
			*val = it->second;
			return true;
		}


	};
}

#endif